package com.sniff.atp.service.purchase;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.dto.SystemLoginDTO;
import com.sniff.atp.enums.api.PurchaseAPI;
import com.sniff.atp.enums.status.PurchaseAbnormalOperationType;
import com.sniff.atp.utils.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.service.purchase
 * @Author: zxy
 * @CreateTime: 2023-02-02 10:00
 * @Description: 采购异常处理
 * @Version: 1.0
 */
@Service
public class PurchaseAbnormalOperationService {

    /**
     * 查询采购异常单
     *
     * @param systemLoginDTO
     * @param purchaseOriginalOrderNo
     * @return
     */
    public String queryOrder(SystemLoginDTO systemLoginDTO, String purchaseOriginalOrderNo) {
        JSONObject param = JsonUtil.readJson("purchase/queryOrder");

        if (purchaseOriginalOrderNo.contains("YCCGD")) {
            param.put("purchasingAbnormalOrderNo", purchaseOriginalOrderNo);
        } else {
            param.put("purchaseOriginalOrderNo", purchaseOriginalOrderNo);
        }

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.QUERY_ORDER.getApi(), param);
    }

    /**
     * 采购异常详情查询
     *
     * @param systemLoginDTO
     * @param purchaseAbnormalOrderId
     * @return
     */
    public String abnormalInfo(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrderId) {
        HashMap<String, String> param = new HashMap<>();
        param.put("purchaseAbnormalOrderId", purchaseAbnormalOrderId);

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doGet(PurchaseAPI.ABNORMAL_INFO.getApi(), param);
    }


    /**
     * 采购异常单处理类型：生成异常参数
     */
    public JSONObject handleAbnormalParam(String purchaseAbnormalOrderId, PurchaseAbnormalOperationType purchaseAbnormalOperationType) {

        JSONObject param = JsonUtil.readJson("purchase/handleAbnormal");
        param.replace("purchaseOperateType", purchaseAbnormalOperationType.getPurchaseOperateType());
        param.replace("purchaseAbnormalOrderId", purchaseAbnormalOrderId);

        if (purchaseAbnormalOperationType.getPurchaseOperateType() == 35 && purchaseAbnormalOperationType.getPurchaseOperateDetailType() == 7) {
            param.put("purchaseOperateDetailType", purchaseAbnormalOperationType.getPurchaseOperateDetailType());

            JSONObject purchaseOnlyReturnMoneyReqDTO = param.getJSONObject("purchaseOnlyReturnMoneyReqDTO");
            purchaseOnlyReturnMoneyReqDTO.replace("purchaseRemakeStatus", 1);
            purchaseOnlyReturnMoneyReqDTO.put("purchaseOperateDetailType", purchaseAbnormalOperationType.getPurchaseOperateDetailType());
            purchaseOnlyReturnMoneyReqDTO.put("purchaseUserProductLink", "https://detail.1688.com/offer/45053974671.html");
            purchaseOnlyReturnMoneyReqDTO.put("purchaseUserProductSku", "7061bd505fb4fbe656a6a62db5ba2a33");
        }

        if (purchaseAbnormalOperationType.getPurchaseOperateType() == 36 && purchaseAbnormalOperationType.getPurchaseOperateDetailType() == 2) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("purchaseRemakeStatus", 2);

            param.put("purchaseReturnAllReqDTO", jsonObject);
            param.remove("purchaseOnlyReturnMoneyReqDTO");
        }

        if (purchaseAbnormalOperationType.getPurchaseOperateType() == 36 && purchaseAbnormalOperationType.getPurchaseOperateDetailType() == 7) {
            param.put("purchaseOperateDetailType", purchaseAbnormalOperationType.getPurchaseOperateDetailType());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("purchaseRemakeStatus", 1);
            jsonObject.put("purchaseUserProductLink", "https://detail.1688.com/offer/45053974671.html");
            jsonObject.put("purchaseUserProductSku", "7061bd505fb4fbe656a6a62db5ba2a33");
            jsonObject.put("purchaseOperateDetailType", purchaseAbnormalOperationType.getPurchaseOperateDetailType());

            param.put("purchaseReturnAllReqDTO", jsonObject);
            param.remove("purchaseOnlyReturnMoneyReqDTO");
        }

        if (purchaseAbnormalOperationType.getPurchaseOperateType() == 30 && purchaseAbnormalOperationType.getPurchaseOperateDetailType() == 21) {
            param.put("purchaseOperateDetailType", purchaseAbnormalOperationType.getPurchaseOperateDetailType());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("refundType", 2);
            param.put("supplierAgreeRefundReqDTO", jsonObject);

            param.remove("purchaseOnlyReturnMoneyReqDTO");
        }

        if (purchaseAbnormalOperationType.getPurchaseOperateType() == 30 && purchaseAbnormalOperationType.getPurchaseOperateDetailType() == 22) {
            param.put("purchaseOperateDetailType", purchaseAbnormalOperationType.getPurchaseOperateDetailType());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("accountType", "1");
            jsonObject.put("alipayAccount", "test");
            jsonObject.put("money", "100");
            jsonObject.put("rejectReason", "自动化脚本执行");
            jsonObject.put("tbAccount", "tester");
            param.put("supplierRejectRefundReqDTO", jsonObject);

            param.remove("purchaseOnlyReturnMoneyReqDTO");
        }


        return param;
    }


    /**
     * 采购异常处理，是否重拍
     */
    public String handleAbnormal(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrderId, PurchaseAbnormalOperationType purchaseAbnormalOperationType) {
        JSONObject param = handleAbnormalParam(purchaseAbnormalOrderId, purchaseAbnormalOperationType);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.HANDLE_ABNORMAL.getApi(), param);
    }

    /**
     * 采购异常处理：供应商退款
     */
    public String applySupplierRefundForOnlyRefundAndReturn(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrderId, String receiveMoney, String tradeNo) {
        JSONObject param = JsonUtil.readJson("purchase/applySupplierRefundForOnlyRefundAndReturn");
        param.replace("purchaseAbnormalOrderId", purchaseAbnormalOrderId);
        param.replace("receiveMoney", receiveMoney);
        param.replace("tradeNo", tradeNo);
        param.replace("receiveMoneyTime", DateUtil.dateToString(new Date()));

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.SUPPLIER_REFUND.getApi(), param);
    }

    /**
     * 采购异常退货退款，填写退货地址
     *
     * @param systemLoginDTO
     * @param purchaseAbnormalOrderId
     * @return
     */
    public String commitWmsAddressReqDTO(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrderId) {
        JSONObject param = JsonUtil.readJson("purchase/commitWmsAddressReqDTO");
        param.replace("purchaseAbnormalOrderId", purchaseAbnormalOrderId);

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.SUPPLIER_REFUND_ALL.getApi(), param);
    }


    /**
     * 采购异常手动对账完成
     */
    public String manualReconciliationCallback(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrder, Integer bizType) {
        JSONArray param = JsonUtil.readJSONArray("purchase/manualReconciliationCallback");
        param.getJSONObject(0).replace("purchasingAbnormalOrderNo", purchaseAbnormalOrder);
        param.getJSONObject(0).replace("bizType", bizType);

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.MANUAL_CALL_BACK.getApi(), param);
    }

    /**
     * 供应商同意退款，对账信息提交
     */
    public String applySupplierRefund(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrderId, String receiveMoney, String tradeNo) {
        JSONObject param = JsonUtil.readJson("purchase/applySupplierRefundForOnlyRefundAndReturn");
        param.replace("purchaseAbnormalOrderId", purchaseAbnormalOrderId);
        param.replace("receiveMoney", receiveMoney);
        param.replace("tradeNo", tradeNo);
        param.replace("receiveMoneyTime", DateUtil.dateToString(new Date()));

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.SUPPLIER_REFUND_RECHANGE.getApi(), param);
    }


    /**
     * 采购异常处理：不重拍，仅退款
     */
    public void supplierOnlyRefound(SystemLoginDTO systemLoginDTO, String purchaseNo) {
        String res = queryOrder(systemLoginDTO, purchaseNo);

        List<String> purchaseAbnormalOrderIds = JsonUtil.extractMultiT(res, "purchaseAbnormalOrderId");

        purchaseAbnormalOrderIds = purchaseAbnormalOrderIds.stream().distinct().collect(Collectors.toList());

        LogUtil.info("采购异常处理:查询采购异常单id, " + purchaseAbnormalOrderIds.toString());

        for (String purchaseAbnormalOrderId : purchaseAbnormalOrderIds) {

            abnormalInfo(systemLoginDTO, purchaseAbnormalOrderId);
            handleAbnormal(systemLoginDTO, purchaseAbnormalOrderId, PurchaseAbnormalOperationType.REFUND_REBEAT);
            LogUtil.info("采购异常处理，选择不重拍");
            applySupplierRefundForOnlyRefundAndReturn(systemLoginDTO, purchaseAbnormalOrderId, "50", "20220919200040011100020019023546");
            LogUtil.info("采购异常处理：供应商退款");
        }
    }


    /**
     * 采购异常处理：不重拍，仅退款
     *
     * @param operatorNode: 1 仅退款-不重拍 2 仅退款-重拍-更换sku 3 退货退款-不重拍 4 退货退款-重拍 5 供应商退款-无需退货 7 供应商拒绝退款
     */
    public void purchaseAbnormal(SystemLoginDTO systemLoginDTO, String purchaseAbnormalOrder, Integer operatorNode) {
        String res = queryOrder(systemLoginDTO, purchaseAbnormalOrder);

        List<String> purchaseAbnormalOrderIds = JsonUtil.extractMultiT(res, "purchaseAbnormalOrderId");

        purchaseAbnormalOrderIds = purchaseAbnormalOrderIds.stream().distinct().collect(Collectors.toList());

        LogUtil.info("采购异常处理:查询采购异常单id, " + purchaseAbnormalOrderIds.toString());

        PurchaseAbnormalOperationType purchaseAbnormalOperationType;

        for (String purchaseAbnormalOrderId : purchaseAbnormalOrderIds) {

            abnormalInfo(systemLoginDTO, purchaseAbnormalOrderId);

            switch (operatorNode) {
                case 1:
                    purchaseAbnormalOperationType = PurchaseAbnormalOperationType.REFUND_REBEAT;
                    break;
                case 2:
                    purchaseAbnormalOperationType = PurchaseAbnormalOperationType.REFUND_CHANGE;
                    break;
                case 3:
                    purchaseAbnormalOperationType = PurchaseAbnormalOperationType.REFUND_BEAT;
                    break;
                case 4:
                    purchaseAbnormalOperationType = PurchaseAbnormalOperationType.REFUND_BEAT_CHANGE;
                    break;
                case 5:
                    purchaseAbnormalOperationType = PurchaseAbnormalOperationType.SUPPLIER_REFUND;
                    break;
                case 7:
                    purchaseAbnormalOperationType = PurchaseAbnormalOperationType.SUPPLIER_REFUND_REFUSE;
                    break;
                default:
                    purchaseAbnormalOperationType = null;
            }

            handleAbnormal(systemLoginDTO, purchaseAbnormalOrderId, purchaseAbnormalOperationType);

            if (operatorNode == 3 || operatorNode == 4) {
                commitWmsAddressReqDTO(systemLoginDTO, purchaseAbnormalOrderId);
            }

            LogUtil.info("采购异常处理，选择不重拍");
            if (operatorNode < 5) {
                applySupplierRefundForOnlyRefundAndReturn(systemLoginDTO, purchaseAbnormalOrderId, "50", "20220919200040011100020019023546");
            }

            if (operatorNode < 7 && operatorNode >= 5) {
                applySupplierRefund(systemLoginDTO, purchaseAbnormalOrderId, "50", "20220919200040011100020019023546");
            }

            LogUtil.info("采购异常处理：供应商退款");
        }
    }
}
